package com.zl.easybuy.util;

import com.zl.easybuy.pojo.User;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpSession;

/**
 * HttpSession的工具类
 */
public class SessionUtils {
    private static final String USER_IN_SESSION = "loginUser";
    private static final String CART_IN_SESSION = "cart";

    //得到当前用户的Session对象
    public static HttpSession getSession(){
        return ((ServletRequestAttributes)(RequestContextHolder.getRequestAttributes())).getRequest().getSession();
    }

    //将用户信息放到Session域中
    public static  void setLoginUserInSession(User loginUser){
        if(loginUser!=null){
            getSession().setAttribute(USER_IN_SESSION,loginUser);
        }
    }
    //从session域中获取登录用户的信息
    public static  User getCurrentUser(){
        return (User)getSession().getAttribute(USER_IN_SESSION);
    }

    public static void invalidSession() {
        getSession().invalidate(); //让session失效
    }

    //从session域获取用户的购物车对象
    public static ShoppingCart getCurrentCart(){
        return   (ShoppingCart) getSession().getAttribute(CART_IN_SESSION);
    }

    //往Session域存放购物车
    public static void setCartInSession(ShoppingCart cart){
        if(cart != null){
            getSession().setAttribute(CART_IN_SESSION,cart);
        }
    }

}
